package com.zsc.newbuds.utils;

import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.zsc.newbuds.entity.User;
import com.zsc.newbuds.service.impl.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Hashtable;

/**
 * 二维码生成
 * @author D
 *二维码生成工具类
 */
@Component
public class QRCodeUtil{

    @Autowired
    UserServiceImpl userService;

    @Autowired
    OssUtil ossUtil;

    /**
     * 编码格式,采用utf-8
     */
    private static final String UNICODE = "utf-8";
    /**
     * 图片格式
     */
    private static final String FORMAT = "JPG";

    private static final int QRCODE_WIDTH = 300;
    private static final int QRCODE_HEIGHT = 300;
    private static final int LOGO_WIDTH = 100;
    private static final int LOGO_HEIGHT = 100;

    /**
     * 生成二维码
     * @param content 内容
     * @param logoPath LOGO地址
     * @param needCompress 是否压缩
     * @return
     * @throws WriterException
     */
    private BufferedImage createImage(String content, String logoPath, boolean needCompress) throws Exception {
        Hashtable<EncodeHintType,Object> hint = new Hashtable<>();
        hint.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
        //设置编码
        hint.put(EncodeHintType.CHARACTER_SET,UNICODE);
        hint.put(EncodeHintType.MARGIN,1);
        BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE,QRCODE_WIDTH,QRCODE_HEIGHT,hint);
        int width = bitMatrix.getWidth();
        int height = bitMatrix.getHeight();
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
            }
        }
        if (logoPath == null || "".equals(logoPath)) {
            return image;
        }
        // 插入图片
        insertImage(image, logoPath, needCompress);
        return image;


    }


    /**
     * 插入logo
     * @param source 二维码地址
     * @param logoPath logo地址
     * @param needCompress 是否雅座
     */
    private void insertImage(BufferedImage source, String logoPath, boolean needCompress) throws Exception {
        File file = new File(logoPath);
        if (!file.exists()) {
            throw new Exception("Logo 地址不存在.");
        }

        Image src = ImageIO.read(new File(logoPath));
        int width = src.getWidth(null);
        int height = src.getHeight(null);
        // 压缩LOGO
        if (needCompress) {
            if (width > LOGO_WIDTH) {
                width = LOGO_WIDTH;
            }
            if (height > LOGO_HEIGHT) {
                height = LOGO_HEIGHT;
            }
            Image image = src.getScaledInstance(width, height, Image.SCALE_SMOOTH);
            BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            Graphics g = tag.getGraphics();
            // 绘制缩小后的图
            g.drawImage(image, 0, 0, null);
            g.dispose();
            src = image;
        }

        // 插入LOGO
        Graphics2D graph = source.createGraphics();
        int x = (QRCODE_WIDTH - width) / 2;
        int y = (QRCODE_HEIGHT - height) / 2;
        graph.drawImage(src, x, y, width, height, null);
        Shape shape = new RoundRectangle2D.Float(x, y, width, width, 6, 6);
        graph.setStroke(new BasicStroke(3f));
        graph.draw(shape);
        graph.dispose();
    }

    /**
     * 生成内嵌logo二维码
     * @param content 二维码内容
     * @param logoPath logo地址
     * @param fileName  文件名字
     * @param needCompress 是否雅座
     * @return 图片地址
     */
    public String encode(String content, String logoPath, String fileName, boolean needCompress){

        System.out.println("运行");
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        BufferedImage image = null;
        String url = "";
        try {
            image = createImage(content, logoPath, needCompress);
            ImageIO.write(image, "png", os);
            InputStream input = new ByteArrayInputStream(os.toByteArray());
            url = ossUtil.upLoadImage(input,"QRCode",fileName);
            return url;
        } catch (Exception e) {
            e.printStackTrace();
            return url;
        }
    }

    /**
     * 生成二维码
     * @param content
     * @param logoPath
     * @param user
     * @param needCompress
     * @throws Exception
     */
    public void createQrCode(String content, String logoPath,User user, boolean needCompress) throws Exception {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        BufferedImage image = createImage(content, logoPath, needCompress);
        ImageIO.write(image, "png", os);
        InputStream input = new ByteArrayInputStream(os.toByteArray());
//        ossUtil.upLoadImage(input,"QRCode",user);
    }


    private void mkdirs(String destPath) {
        File file = new File(destPath);
        if (!file.exists() && !file.isDirectory()) {
            file.mkdirs();
        }
    }

    /**
     * 解析二维码
     * @param path
     * @return
     * @throws Exception
     */
    public String decode(String path) throws Exception {
        File file = new File(path);
        BufferedImage image = ImageIO.read(file);
        if (image == null) {
            return null;
        }
        BufferedImageLuminanceSource source = new BufferedImageLuminanceSource(image);
        BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
        Result result;
        Hashtable<DecodeHintType, Object> hints = new Hashtable<DecodeHintType, Object>();
        hints.put(DecodeHintType.CHARACTER_SET, UNICODE);
        result = new MultiFormatReader().decode(bitmap, hints);
        return result.getText();
    }





}
